package com.compunit.composite.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

import com.compunit.composite.core.interfaces.IResourceExporter;

/**
 * <code>ResourceExporter</code> defines the implementation
 * of the resource exporting utility unit.
 *
 * @author Yi Wang (Neakor)
 * @version Creation date: 11-21-2009 16:59 EST
 * @version Modified date: 12-05-2009 13:59 EST
 */
public class ResourceExporter extends AbstractExporter implements IResourceExporter {
	/**
	 * The <code>Map</code> of <code>String</code>
	 * files names to <code>File</code>.
	 */
	private final Map<String, File> resources;
	
	/**
	 * Constructor of <code>ResourceExporter</code>.
	 */
	public ResourceExporter() {
		this.resources = new HashMap<String, File>();
	}

	@Override
	protected void doExport(final File destination) throws URISyntaxException, IOException {
		final JarOutputStream output = new JarOutputStream(new FileOutputStream(destination));
		for(final String filename : this.resources.keySet()) {
			// Create file entry.
			final File file = this.resources.get(filename);
			output.putNextEntry(new JarEntry(filename));
			// Write in file bytes.
			final FileInputStream fis = new FileInputStream(file);
			int count = 0;
			byte bytes[] = new byte[16384];
			while ((count = fis.read (bytes, 0, bytes.length)) != -1){
				output.write (bytes,0,count);
			}
			fis.close();
		}
		output.close();
	}

	@Override
	public void addResource(final URL url) throws URISyntaxException {
		if(url == null) return;
		final String path = url.getPath();
		final String filename = path.substring(path.lastIndexOf("/")+1, path.length());
		if(this.resources.containsKey(filename)) throw new IllegalArgumentException("Duplicated file name: " + filename);
		this.resources.put(filename, new File(url.toURI()));
	}

	@Override
	public void removeResource(final String filename) {
		if(filename == null) return;
		this.resources.remove(filename);
	}

	@Override
	public boolean containsResource(final String filename) {
		if(filename == null) return false;
		return this.resources.containsKey(filename);
	}

	@Override
	public void cleanup() {
		this.resources.clear();
	}

	@Override
	public boolean isEmpty() {
		return this.resources.isEmpty();
	}
}
